import { StorageTokenKey } from "./config";
import { ReqInterface, ResInterface } from "../interface/request.interface";
import { GetLocal } from "./common";

// 网络请求
export const Request = async ({
  url = '',
  method = 'POST',
  data = {},
  header = {
    'content-type': 'application/json',
  },
}: ReqInterface): Promise<ResInterface> => {
  const _callback: ResInterface = {
    code: 500,
    data: {},
    message: '网络错误',
  }
  const _GetLocal = await GetLocal(StorageTokenKey);
  const _token = _GetLocal.token || '';
  console.log('_GetLocal', _GetLocal)
  return new Promise((resolve) => {
    const _header: any = {
      ...header,
      'authorization': _token,
    }
    wx.request({
      url,
      method,
      data,
      header: _header,
      success: (res: any) => {
        const { errMsg, data } = res;
        if (errMsg === 'request:ok') {
          _callback.code = data['code'] || 200;
          _callback.data = data['data'];
          _callback.message = data['message'] || '请求成功';
        }
        resolve(_callback);
      },
      fail: () => {
        resolve(_callback);
      },
    });
  });
}